#include "PersonalDiary.h"
#include <fstream>
#include <iostream>

using namespace std;

PersonalDiary::PersonalDiary(const string& data_file) : data_file(data_file) {
    //读取日记集储存文件来构造日记集
    readFromFile();
}

bool PersonalDiary::addEntity(const string& date, const string& content) {
    //向日记集中添加日记并更新储存文件
    entities[date] = content;
    WriteToFile();
    return true;
}

bool PersonalDiary::removeEntity(const string& date) {
    //从日记集中删除日记并更新储存文件
    auto it = entities.find(date);
    if (it != entities.end()) {
        entities.erase(it);
        WriteToFile();
        return true;
    }
    return false;
}

map<string,string> PersonalDiary::listEntities(const string& start, const string& end) const {
    //从日记集中获取指定日期之间的某些日记
    map<string,string> result;
    for (const auto& entity: entities) {
        if ((start.empty()||entity.first >= start) && (end.empty()||entity.first <= end)) {
            result[entity.first] = entity.second;
        }
    }
    return result;
}

string PersonalDiary::showEntity(const string& date) const{
    //从日记集中获取指定日期的某个日记
    auto it = entities.find(date);
    if (it!= entities.end()) {
        return it->second;
    }
    return "";
}

bool PersonalDiary::readFromFile() {
    //读取日记集储存文件
    ifstream file(data_file);
    if (!file.is_open()) {
        cout<<"Error: Couldn't open file for reading."<<endl;
        return false;
    }
    entities.clear();
    string line;
    while (getline(file,line)){
        size_t pos = line.find(':');
        if (pos != string::npos) {
            string date = line.substr(0, pos);
            string content = "";
            while(getline(file, line)){
                if (line.find("##end##") != string::npos){
                    content += "\n ##end##";
                    break;
                }
                content += "\n" + line;
            }
            entities[date] = content;
        }
    }
    file.close();
    return true;
}

void PersonalDiary:: WriteToFile() const{
    //更新日记集储存文件
    ofstream file(data_file,ios::trunc);
    if (!file.is_open()) {
        cout<<"Error: Couldn't open file for writing."<<endl;
        return;
    }
    for (const auto& entity :entities) {
        file << entity.first << ":" << entity.second << endl;
    }
    file.close();
}